In [3]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
In [3]:
np.random.seed(1000)
y=np.random.standard_normal(20)
In [4]:
y
Out[4]:
array([-0.8044583 ,  0.32093155, -0.02548288,  0.64432383, -0.30079667,
        0.38947455, -0.1074373 , -0.47998308,  0.5950355 , -0.46466753,
        0.66728131, -0.80611561, -1.19606983, -0.40596016, -0.18237734,
        0.10319289, -0.13842199,  0.70569237,  1.27179528, -0.98674733])
In [5]:
x=range(len(y))
In [6]:
x
Out[6]:
range(0, 20)
In [7]:
plt.plot(x,y)
plt.show()
In [8]:
plt.plot(y) #接收数组数据
plt.show()
In [9]:
plt.plot(y.cumsum())
plt.show()
In [10]:
plt.plot(y.cumsum())
plt.grid(True)
plt.axis('tight')
Out[10]:
(-0.9500000000000001, 19.95, -2.322818663749045, 0.5655085808655865)
In [11]:
plt.plot(y.cumsum())
plt.grid(True)
plt.xlim(-1,20)
plt.ylim(np.min(y.cumsum())-1,np.max(y.cumsum())+1)
Out[11]:
(-3.1915310617211072, 1.4342209788376488)
In [12]:
plt.figure(figsize=(7,4))
plt.plot(y.cumsum(),'b',lw=1.5)
plt.plot(y.cumsum(),'ro')
plt.grid(True)
plt.axis('tight')
plt.xlabel('Index')
plt.xlabel('value')
plt.title('A smple plot')
Out[12]:
Text(0.5, 1.0, 'A smple plot')
In [13]:
np.random.seed(2000)
y=np.random.standard_normal((20,2)).cumsum(axis=0)
y
Out[13]:
array([[ 1.73673761,  1.89791391],
       [-0.37003581,  1.74900181],
       [ 0.21302575, -0.51023122],
       [ 0.35026529, -1.21144444],
       [-0.27051479, -1.6910642 ],
       [ 0.93922398, -2.76624806],
       [ 1.74614319, -3.05703153],
       [ 1.52519555, -3.22618757],
       [ 2.62602999, -3.14367705],
       [ 2.6216544 , -4.8662353 ],
       [ 3.67921082, -7.38414811],
       [ 1.7685707 , -6.07769276],
       [ 2.19296834, -6.54686084],
       [ 1.18689581, -7.46878388],
       [ 1.81330034, -7.11160718],
       [ 1.79458178, -6.89043591],
       [ 2.49318589, -6.05592589],
       [ 0.82754806, -8.95736573],
       [ 0.77890953, -9.00274406],
       [ 2.25424343, -9.51643749]])
In [14]:
plt.figure(figsize=(7,4))
plt.plot(y,lw=1.5)
plt.plot(y,'ro')
plt.grid(True)
plt.axis('tight')
plt.xlabel('Index')
plt.xlabel('value')
plt.title('A smple plot')
Out[14]:
Text(0.5, 1.0, 'A smple plot')
In [15]:
plt.figure(figsize=(7,4))
plt.plot(y[:,0],lw=1.5,label='1st')
plt.plot(y[:,1],lw=1.5,label='2nd')
plt.plot(y,'ro')
plt.grid(True)
plt.legend(loc=0)
plt.axis('tight')
plt.xlabel('Index')
plt.xlabel('value')
plt.title('A smple plot')
Out[15]:
Text(0.5, 1.0, 'A smple plot')
In [16]:
y[:,0]=y[:,0]*100
plt.figure(figsize=(7,4))
plt.plot(y[:,0],lw=1.5,label='1st')
plt.plot(y[:,1],lw=1.5,label='2nd')
plt.plot(y,'ro')
plt.grid(True)
plt.legend(loc=0)
plt.axis('tight')
plt.xlabel('Index')
plt.xlabel('value')
plt.title('A smple plot')
Out[16]:
Text(0.5, 1.0, 'A smple plot')
In [17]:
# 使用双轴图
fig,ax1=plt.subplots()
plt.plot(y[:,0],'b',lw=1.5,label='1st')
plt.plot(y[:,0],'ro')
plt.grid(True)
plt.legend(loc=0)
plt.axis('tight')
plt.xlabel('Index')
plt.ylabel('value 1st')
plt.title('A smple plot')

         
ax2=ax1.twinx()
plt.plot(y[:,1],'g',lw=1.5,label='2nd')
plt.plot(y[:,1],'ro')
plt.legend(loc=0)
plt.ylabel('value 2nd')
Out[17]:
Text(0, 0.5, 'value 2nd')
In [18]:
#画两张子图
plt.figure(figsize=(7,5))
plt.subplot(211)
plt.plot(y[:,0],'b',lw=1.5,label='1st')
plt.plot(y[:,0],'ro')
plt.grid(True)
plt.legend(loc=0)
plt.axis('tight')
plt.xlabel('Index')
plt.ylabel('value 1st')
plt.title('A smple plot')
plt.subplot(212)
plt.plot(y[:,1],'g',lw=1.5,label='2nd')
plt.plot(y[:,1],'ro')
plt.grid(True)
plt.legend(loc=0)
plt.axis('tight')
plt.xlabel('Index')
plt.ylabel('value 2nd')
plt.title('A smple plot')
Out[18]:
Text(0.5, 1.0, 'A smple plot')
In [19]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.figure(figsize=(9,4))
plt.subplot(121)
plt.plot(y[:,0],'b',lw=1.5,label='1st')
plt.plot(y[:,0],'ro')
plt.grid(True)
plt.legend(loc=0)
plt.axis('tight')
plt.xlabel('Index')
plt.ylabel('value 1st')
plt.title('1st data set')
plt.subplot(122)
plt.bar(np.arange(len(y)),y[:,1],width=0.5,color='g',label='2nd')
plt.grid(True)
plt.legend(loc=0)
plt.axis('tight')
plt.xlabel('Index')
plt.ylabel('value 2nd')
plt.title('2nd data set')
Out[19]:
Text(0.5, 1.0, '2nd data set')
In [20]:
y=np.random.standard_normal((1000,2))
plt.figure(figsize=(7,5))
plt.plot(y[:,0],y[:,1],'ro')
plt.grid(True)
plt.xlabel('1st')
plt.ylabel('2nd')
plt.title('Scatter Plot')
Out[20]:
Text(0.5, 1.0, 'Scatter Plot')
In [21]:
y=np.random.standard_normal((1000,2))
plt.figure(figsize=(20,10))
plt.plot(y[:,0],y[:,1],'ro',marker='o')
plt.grid(True)
plt.xlabel('1st')
plt.ylabel('2nd')
plt.title('Scatter Plot')
Out[21]:
Text(0.5, 1.0, 'Scatter Plot')
In [22]:
#加入权重
c=np.random.randint(0,10,len(y))
plt.figure(figsize=(7,5))
plt.scatter(y[:,0],y[:,1],c=c)
plt.colorbar()
plt.grid(True)
plt.xlabel('1st')
plt.ylabel('2nd')
plt.title('Scatter Plot')
Out[22]:
Text(0.5, 1.0, 'Scatter Plot')
In [23]:
plt.figure(figsize=(7,4))
plt.hist(y,label=['1st','2nd'],bins=25)
plt.grid(True)
plt.xlabel('value')
plt.ylabel('frequency')
plt.title('Histgram')
Out[23]:
Text(0.5, 1.0, 'Histgram')
In [24]:
plt.figure(figsize=(7,4))
plt.hist(y,label=['1st','2nd'],bins=25,cumulative=True)
plt.grid(True)
plt.xlabel('value')
plt.ylabel('frequency')
plt.title('Histgram')
Out[24]:
Text(0.5, 1.0, 'Histgram')
In [25]:
plt.figure(figsize=(7,4))
plt.hist(y,label=['1st','2nd'],color=['b','g'],stacked=True,bins=25,edgecolor="black")
plt.grid(True)
plt.legend(loc=0)
plt.xlabel('value')
plt.ylabel('frequency')
plt.title('Histgram')
Out[25]:
Text(0.5, 1.0, 'Histgram')
In [26]:
fig,ax=plt.subplots(figsize=(7,4))
plt.boxplot(y)
plt.grid(True)
plt.setp(ax,xticklabels=['1st','2nd'])
plt.xlabel('data set')
plt.ylabel('value')
plt.title('boxplot')
Out[26]:
Text(0.5, 1.0, 'boxplot')
In [27]:
plt.figure(figsize=(20,100))
line=plt.plot(y,'g')
plt.setp(line,linestyle='-')
Out[27]:
[None, None]
In [48]:
def func(x):
	return 0.5*np.exp(x)+1

a,b=0.5,1.5
x=np.linspace(0,2)
y=func(x)

fig,ax=plt.subplots(figsize=(7,5))
plt.plot(x,y,'b',linewidth=2)
plt.ylim(ymin=0)
Out[48]:
(0, 4.8542544519385915)
In [60]:
Ix=np.linspace(a,b)
Iy=func(Ix)
verts=[(a,0)]+list(zip(Ix,Iy))+[(b,0)]
verts
q=[list(zip(Ix,Iy))]
type(q)
verts.count((0.5,0))
Out[60]:
1
In [65]:
from matplotlib.patches import Polygon
poly=Polygon(verts,facecolor='0.7',edgecolor='0.5')

fig,ax=plt.subplots(figsize=(7,5))
plt.plot(x,y,'b',linewidth=2)
plt.ylim(ymin=0)
ax.add_patch(poly)
Out[65]:
<matplotlib.patches.Polygon at 0x2755f902cc0>
In [69]:
from matplotlib.patches import Polygon
poly=Polygon(verts,facecolor='0.7',edgecolor='0.5')

fig,ax=plt.subplots(figsize=(7,5))
plt.plot(x,y,'b',linewidth=2)
plt.ylim(ymin=0)
ax.add_patch(poly)
plt.text(0.5*(a+b),1,r"$\int_a^b f(x)\mathrm{d}x$",horizontalalignment='center',fontsize=20)
plt.figtext(0.9,0.075,'$x$')
plt.figtext(0.075,0.9,'$f(x)$')
ax.set_xticks((a,b))
ax.set_xticklabels(('$a$','$b$'))
ax.set_yticks([func(a),func(b)])
ax.set_yticklabels(('$f(a)$','$f(b)$'))
plt.grid(True)
In [125]:
import mpl_finance as mpf
import tushare as ts
start=(2014,5,1)
end=(2014,6,30)
wdyx = ts.get_k_data('000651','2019-08-01')
In [126]:
wdyx.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 31 entries, 136 to 166
Data columns (total 7 columns):
date      31 non-null object
open      31 non-null float64
close     31 non-null float64
high      31 non-null float64
low       31 non-null float64
volume    31 non-null float64
code      31 non-null object
dtypes: float64(5), object(2)
memory usage: 1.9+ KB
In [127]:
wdyx[:3]
Out[127]:
date open close high low volume code
136 2019-08-01 55.0 53.68 55.00 53.38 482956.0 000651
137 2019-08-02 52.0 53.43 53.63 51.31 411599.0 000651
138 2019-08-05 53.4 52.98 53.80 52.66 394928.0 000651
In [128]:
from matplotlib.pylab import date2num
import datetime
In [129]:
def date_to_num(dates):
    num_time = []
    for date in dates:
        date_time = datetime.datetime.strptime(date,'%Y-%m-%d')
        num_date = date2num(date_time)
        num_time.append(num_date)
    return num_time
In [130]:
# dataframe轉換為二維陣列
mat_wdyx = wdyx.values
In [131]:
mat_wdyx
Out[131]:
array([['2019-08-01', 55.0, 53.68, 55.0, 53.38, 482956.0, '000651'],
       ['2019-08-02', 52.0, 53.43, 53.63, 51.31, 411599.0, '000651'],
       ['2019-08-05', 53.4, 52.98, 53.8, 52.66, 394928.0, '000651'],
       ['2019-08-06', 50.6, 50.93, 51.3, 49.05, 532003.0, '000651'],
       ['2019-08-07', 51.1, 50.27, 51.45, 50.26, 242402.0, '000651'],
       ['2019-08-08', 50.5, 51.0, 51.44, 50.42, 296270.0, '000651'],
       ['2019-08-09', 51.03, 49.94, 51.29, 49.68, 391730.0, '000651'],
       ['2019-08-12', 49.8, 50.38, 50.49, 49.6, 235654.0, '000651'],
       ['2019-08-13', 50.65, 51.36, 52.3, 50.65, 498999.0, '000651'],
       ['2019-08-14', 52.73, 51.56, 53.0, 51.5, 323715.0, '000651'],
       ['2019-08-15', 50.56, 51.3, 51.35, 50.16, 226727.0, '000651'],
       ['2019-08-16', 51.2, 51.25, 51.68, 50.6, 289949.0, '000651'],
       ['2019-08-19', 51.8, 52.42, 52.5, 51.55, 344397.0, '000651'],
       ['2019-08-20', 52.4, 52.79, 53.09, 52.02, 317058.0, '000651'],
       ['2019-08-21', 52.6, 54.54, 55.2, 52.58, 664284.0, '000651'],
       ['2019-08-22', 54.99, 54.88, 55.45, 54.51, 368523.0, '000651'],
       ['2019-08-23', 55.1, 54.89, 55.39, 54.51, 325909.0, '000651'],
       ['2019-08-26', 53.46, 54.17, 54.48, 53.26, 338864.0, '000651'],
       ['2019-08-27', 54.41, 55.35, 55.99, 54.41, 472372.0, '000651'],
       ['2019-08-28', 55.78, 55.32, 55.79, 55.01, 243395.0, '000651'],
       ['2019-08-29', 55.5, 54.78, 55.74, 54.02, 302430.0, '000651'],
       ['2019-08-30', 55.32, 55.5, 55.95, 55.02, 410238.0, '000651'],
       ['2019-09-02', 56.95, 57.47, 57.82, 56.7, 684288.0, '000651'],
       ['2019-09-03', 58.41, 57.8, 58.43, 57.1, 511978.0, '000651'],
       ['2019-09-04', 57.79, 59.85, 59.85, 57.3, 644380.0, '000651'],
       ['2019-09-05', 59.91, 58.87, 60.56, 58.81, 483040.0, '000651'],
       ['2019-09-06', 59.2, 58.8, 59.2, 58.0, 385050.0, '000651'],
       ['2019-09-09', 59.19, 59.34, 59.89, 59.0, 375943.0, '000651'],
       ['2019-09-10', 59.8, 59.4, 60.12, 59.24, 246978.0, '000651'],
       ['2019-09-11', 59.4, 58.7, 59.44, 58.01, 310354.0, '000651'],
       ['2019-09-12', 59.07, 59.61, 59.79, 59.06, 274926.0, '000651']],
      dtype=object)
In [132]:
num_time = date_to_num(mat_wdyx[:,0])
In [133]:
num_time
Out[133]:
[737272.0,
 737273.0,
 737276.0,
 737277.0,
 737278.0,
 737279.0,
 737280.0,
 737283.0,
 737284.0,
 737285.0,
 737286.0,
 737287.0,
 737290.0,
 737291.0,
 737292.0,
 737293.0,
 737294.0,
 737297.0,
 737298.0,
 737299.0,
 737300.0,
 737301.0,
 737304.0,
 737305.0,
 737306.0,
 737307.0,
 737308.0,
 737311.0,
 737312.0,
 737313.0,
 737314.0]
In [134]:
mat_wdyx[:,0] = num_time
In [135]:
mat_wdyx[:20]
Out[135]:
array([[737272.0, 55.0, 53.68, 55.0, 53.38, 482956.0, '000651'],
       [737273.0, 52.0, 53.43, 53.63, 51.31, 411599.0, '000651'],
       [737276.0, 53.4, 52.98, 53.8, 52.66, 394928.0, '000651'],
       [737277.0, 50.6, 50.93, 51.3, 49.05, 532003.0, '000651'],
       [737278.0, 51.1, 50.27, 51.45, 50.26, 242402.0, '000651'],
       [737279.0, 50.5, 51.0, 51.44, 50.42, 296270.0, '000651'],
       [737280.0, 51.03, 49.94, 51.29, 49.68, 391730.0, '000651'],
       [737283.0, 49.8, 50.38, 50.49, 49.6, 235654.0, '000651'],
       [737284.0, 50.65, 51.36, 52.3, 50.65, 498999.0, '000651'],
       [737285.0, 52.73, 51.56, 53.0, 51.5, 323715.0, '000651'],
       [737286.0, 50.56, 51.3, 51.35, 50.16, 226727.0, '000651'],
       [737287.0, 51.2, 51.25, 51.68, 50.6, 289949.0, '000651'],
       [737290.0, 51.8, 52.42, 52.5, 51.55, 344397.0, '000651'],
       [737291.0, 52.4, 52.79, 53.09, 52.02, 317058.0, '000651'],
       [737292.0, 52.6, 54.54, 55.2, 52.58, 664284.0, '000651'],
       [737293.0, 54.99, 54.88, 55.45, 54.51, 368523.0, '000651'],
       [737294.0, 55.1, 54.89, 55.39, 54.51, 325909.0, '000651'],
       [737297.0, 53.46, 54.17, 54.48, 53.26, 338864.0, '000651'],
       [737298.0, 54.41, 55.35, 55.99, 54.41, 472372.0, '000651'],
       [737299.0, 55.78, 55.32, 55.79, 55.01, 243395.0, '000651']],
      dtype=object)
In [146]:
fig,ax=plt.subplots(figsize=(8,5))
fig.subplots_adjust(bottom=0.2)
# mpf.candlestick_ohlc(ax,mat_wdyx[:20],width=0.6,colorup='r',colordown='g')
mpf.candlestick_ochl(ax,mat_wdyx[:20],width=0.2,colorup='r',colordown='g',alpha=1.0)
plt.grid(True)
ax.xaxis_date()  #设置x轴日期
ax.autoscale_view() #自动调整一下视图
plt.xticks(rotation=30)
Out[146]:
(array([737272., 737276., 737280., 737284., 737288., 737292., 737296.,
        737300.]), <a list of 8 Text xticklabel objects>)

存在问题:mpf的蜡烛图生成有问题?

改用candlestick_ochl解决了问题

In [150]:
fig,ax=plt.subplots(figsize=(8,5))
fig.subplots_adjust(bottom=0.2)
mpf.plot_day_summary_oclh(ax,mat_wdyx[:20],colorup='b',colordown='r')
plt.grid(True)
ax.xaxis_date()  #设置x轴日期
ax.autoscale_view() #自动调整一下视图
plt.xticks(rotation=30)
Out[150]:
(array([737272., 737276., 737280., 737284., 737288., 737292., 737296.,
        737300.]), <a list of 8 Text xticklabel objects>)
In [151]:
mat_wdyx
Out[151]:
array([[737272.0, 55.0, 53.68, 55.0, 53.38, 482956.0, '000651'],
       [737273.0, 52.0, 53.43, 53.63, 51.31, 411599.0, '000651'],
       [737276.0, 53.4, 52.98, 53.8, 52.66, 394928.0, '000651'],
       [737277.0, 50.6, 50.93, 51.3, 49.05, 532003.0, '000651'],
       [737278.0, 51.1, 50.27, 51.45, 50.26, 242402.0, '000651'],
       [737279.0, 50.5, 51.0, 51.44, 50.42, 296270.0, '000651'],
       [737280.0, 51.03, 49.94, 51.29, 49.68, 391730.0, '000651'],
       [737283.0, 49.8, 50.38, 50.49, 49.6, 235654.0, '000651'],
       [737284.0, 50.65, 51.36, 52.3, 50.65, 498999.0, '000651'],
       [737285.0, 52.73, 51.56, 53.0, 51.5, 323715.0, '000651'],
       [737286.0, 50.56, 51.3, 51.35, 50.16, 226727.0, '000651'],
       [737287.0, 51.2, 51.25, 51.68, 50.6, 289949.0, '000651'],
       [737290.0, 51.8, 52.42, 52.5, 51.55, 344397.0, '000651'],
       [737291.0, 52.4, 52.79, 53.09, 52.02, 317058.0, '000651'],
       [737292.0, 52.6, 54.54, 55.2, 52.58, 664284.0, '000651'],
       [737293.0, 54.99, 54.88, 55.45, 54.51, 368523.0, '000651'],
       [737294.0, 55.1, 54.89, 55.39, 54.51, 325909.0, '000651'],
       [737297.0, 53.46, 54.17, 54.48, 53.26, 338864.0, '000651'],
       [737298.0, 54.41, 55.35, 55.99, 54.41, 472372.0, '000651'],
       [737299.0, 55.78, 55.32, 55.79, 55.01, 243395.0, '000651'],
       [737300.0, 55.5, 54.78, 55.74, 54.02, 302430.0, '000651'],
       [737301.0, 55.32, 55.5, 55.95, 55.02, 410238.0, '000651'],
       [737304.0, 56.95, 57.47, 57.82, 56.7, 684288.0, '000651'],
       [737305.0, 58.41, 57.8, 58.43, 57.1, 511978.0, '000651'],
       [737306.0, 57.79, 59.85, 59.85, 57.3, 644380.0, '000651'],
       [737307.0, 59.91, 58.87, 60.56, 58.81, 483040.0, '000651'],
       [737308.0, 59.2, 58.8, 59.2, 58.0, 385050.0, '000651'],
       [737311.0, 59.19, 59.34, 59.89, 59.0, 375943.0, '000651'],
       [737312.0, 59.8, 59.4, 60.12, 59.24, 246978.0, '000651'],
       [737313.0, 59.4, 58.7, 59.44, 58.01, 310354.0, '000651'],
       [737314.0, 59.07, 59.61, 59.79, 59.06, 274926.0, '000651']],
      dtype=object)
In [162]:
fig,(ax1,ax2)=plt.subplots(2,sharex=True,figsize=(8,5))
mpf.candlestick_ochl(ax1,mat_wdyx,width=0.6,colorup='b',colordown='r')
ax1.set_title('geli')
ax1.set_ylabel('price')
ax1.grid(True)
ax1.xaxis_date()
plt.bar(mat_wdyx[:,0]-0.25,mat_wdyx[:,5],width=0.5)
ax2.set_ylabel('volume')
ax2.grid(True)
ax2.autoscale_view()
plt.xticks(rotation=30)
Out[162]:
(array([737272., 737279., 737286., 737293., 737303., 737310.]),
 <a list of 6 Text xticklabel objects>)
In [5]:
#绘制三维图
strike=np.linspace(50,150,24)
ttm=np.linspace(0.5,2.5,24)
strike,ttm=np.meshgrid(strike,ttm)

strike[:2]

iv=(strike-100)**2/(100*strike)/ttm

from mpl_toolkits.mplot3d import Axes3D

fig=plt.figure(figsize=(9,6))
ax=fig.gca(projection='3d')

surf=ax.plot_surface(strike,ttm,iv,rstride=2,cstride=2,cmap=plt.cm.coolwarm,linewidth=0.5,antialiased=True)
ax.set_xlabel("strike")
ax.set_ylabel("time-to-maturity")
ax.set_zlabel("implied volatility")
fig.colorbar(surf,shrink=0.5,aspect=5)
Out[5]:
<matplotlib.colorbar.Colorbar at 0x1778e283e80>
In [9]:
#三维散点图
fig=plt.figure(figsize=(8,5))
ax=fig.add_subplot(111,projection='3d')
ax.view_init(30,60)
ax.scatter(strike,ttm,iv,zdir='z',s=25,c='b',marker='^')
ax.set_xlabel('strike')
ax.set_ylabel("time-to-maturity")
ax.set_zlabel("implied volatility")
Out[9]:
Text(0.5, 0, 'implied volatility')
In [ ]: